/**
 * 
 */
package com.huawei.esdk.uc.sametime.history.ui;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.ColumnPixelData;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MenuEvent;
import org.eclipse.swt.events.MenuListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.part.ViewPart;

import com.huawei.esdk.uc.jna.Constants.CallHistoryType;
import com.huawei.esdk.uc.jna.struct.STCallHistroyItem;
import com.huawei.esdk.uc.jna.struct.STConfPartItem;
import com.huawei.esdk.uc.jna.struct.STTime;
import com.huawei.esdk.uc.jna.util.StringUtil;
import com.huawei.esdk.uc.sametime.ConstantsDefines.CallStatus;
import com.huawei.esdk.uc.sametime.history.HistoryListConstants;
import com.huawei.esdk.uc.sametime.international.Messages;
import com.huawei.esdk.uc.sametime.models.ConfHistItem;
import com.huawei.esdk.uc.sametime.models.Participant;
import com.huawei.esdk.uc.sametime.models.ParticipantList;
import com.huawei.esdk.uc.sametime.services.UCCallService;
import com.huawei.esdk.uc.sametime.services.UCHistoryService;
import com.huawei.esdk.uc.sametime.util.GlobalConfiguration;
import com.huawei.esdk.uc.sametime.util.ImageFactory;
import com.huawei.esdk.uc.sametime.util.PluginUtil;
import com.huawei.esdk.uc.sametime.widgets.EsdkUCConvWindow;

/**
 * 呼叫及会议历史记录
 * @author lWX169831
 * 
 */
public class EsdkUCHistoryView extends ViewPart
{
    private Logger logger = Logger.getLogger(EsdkUCHistoryView.class);

    private static EsdkUCHistoryView instance;

    private TableViewer callHistTableViewer;

    private TableViewer confHistTableViewer;

    private Table callHistTableCtl;

    private Table confHistTableCtl;

    private static String callColumnHeaders[] = new String[HistoryListConstants.CALL_COLUMN_COUNT];

    private static String confColumnHeaders[] = new String[HistoryListConstants.CONF_COLUMN_COUNT];

    private List<STCallHistroyItem> callHistoryItems = new ArrayList<STCallHistroyItem>();

    private List<ConfHistItem> confHistoryItems = new ArrayList<ConfHistItem>();

    private static final int MAX_INDEX = 100;

    private int historyIndex = MAX_INDEX;

    /**
	 * 
	 */
    public EsdkUCHistoryView()
    {
        super();
        // instance = this;
        // 在非静态方法中修改类的静态变量，在CI中出错了
        EsdkUCHistoryView.initInstance(this);
    }

    public static EsdkUCHistoryView getInstance()
    {
        return instance;
    }

    public static void initInstance(EsdkUCHistoryView ucHistoryView)
    {
        instance = ucHistoryView;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets
     * .Composite)
     */
    @Override
    public void createPartControl(Composite parent)
    {
        createTabFolder(parent);
    }

    /*
     * @创建面板选项卡(TabFolder)
     */
    private void createTabFolder(Composite parent)
    {
        final TabFolder tabFolder = new TabFolder(parent, SWT.TOP);
        tabFolder.setLayout(new FillLayout());

        TabItem callItem = new TabItem(tabFolder, SWT.NONE);
        callItem.setText(Messages.EsdkUCHistoryView_CALL_HISTORY);
        callItem.setImage(ImageFactory.loadImage(Display.getCurrent(),
                ImageFactory.CLICK_TO_CALL));
        // 创建呼叫记录列表
        createCallHistTable(tabFolder);
        callItem.setControl(callHistTableCtl);

        TabItem confItem = new TabItem(tabFolder, SWT.NONE);
        confItem.setText(Messages.EsdkUCHistoryView_CONFERENCE_HISTORY);
        confItem.setImage(ImageFactory.loadImage(Display.getCurrent(),
                ImageFactory.CLICK_TO_CONF));
        // 创建会议记录列表
        createConfHistTable(tabFolder);
        confItem.setControl(confHistTableCtl);
    }

    private void createCallHistTable(Composite parent)
    {
        if (null != callHistTableCtl)
        {
            callHistTableCtl.dispose();
        }
        callHistTableViewer = new TableViewer(parent, SWT.SINGLE
                | SWT.FULL_SELECTION | SWT.VERTICAL);
        callHistTableCtl = callHistTableViewer.getTable();

        createCallHistTableColumns();
        createCallHistTableContextMenu();
        createCallTableHelpers();

        setTableLayout(callHistTableCtl);

        freshCallHistory();
    }

    /**
     * 刷新呼叫历史记录表格
     */
    public void freshCallHistory()
    {
        logger.debug("fresh Call History");
        if (null != callHistoryItems)
        {
            callHistoryItems.clear();
        }
        callHistoryItems = UCHistoryService.getCallHistData(
                CallHistoryType.HISTORY_CALL_ALL, 0, historyIndex);

        callHistTableViewer.setInput(callHistoryItems);

        if (null != callHistTableCtl)
        {
            for (int i = 0; i < HistoryListConstants.CALL_COLUMN_COUNT; i++)
            {
                callHistTableCtl.getColumn(i).pack();
            }
        }
    }

    private void createConfHistTable(Composite parent)
    {
        if (null != confHistTableCtl)
        {
            confHistTableCtl.dispose();
        }
        confHistTableViewer = new TableViewer(parent, SWT.SINGLE
                | SWT.FULL_SELECTION | SWT.VERTICAL);
        confHistTableCtl = confHistTableViewer.getTable();

        createConfHistTableColumns();
        createConfHistTableContextMenu();
        createConfTableHelpers();

        setTableLayout(confHistTableCtl);

        freshConvHistory();
    }

    /**
     * 刷新历史记录表格中的数据
     */
    public void freshConvHistory()
    {
        logger.debug("fresh conf History");

        if (null != confHistoryItems)
        {
            confHistoryItems.clear();
        }
        confHistoryItems = UCHistoryService.getConfHistData(0, historyIndex);

        confHistTableViewer.setInput(confHistoryItems);

        if (null != confHistTableCtl)
        {
            for (int i = 0; i < HistoryListConstants.CONF_COLUMN_COUNT; i++)
            {
                confHistTableCtl.getColumn(i).pack();
            }
        }
    }

    /**
     * 生成呼叫历史记录表格的表头
     */
    private void createCallHistTableColumns()
    {
        TableColumn tc;

        callColumnHeaders[HistoryListConstants.CALL_STATUS_COLUMN] = Messages.EsdkUCHistoryView_CALLTABLE_HEADER_STATUS;
        callColumnHeaders[HistoryListConstants.NAME_COLUMN] = Messages.EsdkUCHistoryView_CALLTABLE_HEADER_NAME;
        callColumnHeaders[HistoryListConstants.PHONE_COLUMN] = Messages.EsdkUCHistoryView_CALLTABLE_HEADER_PHONE;
        callColumnHeaders[HistoryListConstants.CALL_DURATION_COLUMN] = Messages.DURATION;
        callColumnHeaders[HistoryListConstants.CALL_TIME_COLUMN] = Messages.TIME;

        callHistTableCtl.setHeaderVisible(true);

        tc = new TableColumn(callHistTableCtl, SWT.NONE);
        tc.setText(callColumnHeaders[HistoryListConstants.CALL_STATUS_COLUMN]);
        tc.setAlignment(SWT.CENTER);

        tc = new TableColumn(callHistTableCtl, SWT.NONE);
        tc.setText(callColumnHeaders[HistoryListConstants.NAME_COLUMN]);
        tc.setAlignment(SWT.CENTER);

        tc = new TableColumn(callHistTableCtl, SWT.NONE);
        tc.setText(callColumnHeaders[HistoryListConstants.PHONE_COLUMN]);
        tc.setAlignment(SWT.CENTER);

        tc = new TableColumn(callHistTableCtl, SWT.NONE);
        tc
                .setText(callColumnHeaders[HistoryListConstants.CALL_DURATION_COLUMN]);
        tc.setAlignment(SWT.CENTER);

        tc = new TableColumn(callHistTableCtl, SWT.NONE);
        tc.setText(callColumnHeaders[HistoryListConstants.CALL_TIME_COLUMN]);
        tc.setAlignment(SWT.CENTER);

    }

    /**
     * 生成会议历史记录表格的表头
     */
    private void createConfHistTableColumns()
    {
        TableColumn tc;

        confColumnHeaders[HistoryListConstants.INITIATOR_COLUMN] = Messages.EsdkUCHistoryView_CONFTABLE_HEADER_INITIATOR;
        confColumnHeaders[HistoryListConstants.PARTICIPANTS_COLUMN] = Messages.EsdkUCHistoryView_CONFTABLE_HEADER_PARTICIPANTS;
        confColumnHeaders[HistoryListConstants.CONF_DURATION_COLUMN] = Messages.DURATION;
        confColumnHeaders[HistoryListConstants.CONF_TIME_COLUMN] = Messages.TIME;

        confHistTableCtl.setHeaderVisible(true);

        tc = new TableColumn(confHistTableCtl, SWT.NONE);
        tc.setText(confColumnHeaders[HistoryListConstants.INITIATOR_COLUMN]);
        tc.setAlignment(SWT.CENTER);

        tc = new TableColumn(confHistTableCtl, SWT.NONE);
        tc.setText(confColumnHeaders[HistoryListConstants.PARTICIPANTS_COLUMN]);
        tc.setAlignment(SWT.CENTER);

        tc = new TableColumn(confHistTableCtl, SWT.NONE);
        tc
                .setText(confColumnHeaders[HistoryListConstants.CONF_DURATION_COLUMN]);
        tc.setAlignment(SWT.CENTER);

        tc = new TableColumn(confHistTableCtl, SWT.NONE);
        tc.setText(confColumnHeaders[HistoryListConstants.CONF_TIME_COLUMN]);
        tc.setAlignment(SWT.CENTER);

    }

    /**
     * 生成呼叫历史记录表格中的上下文菜单
     */
    private void createCallHistTableContextMenu()
    {
        MenuManager menuManager = new MenuManager();
        menuManager.add(new RemoveCallItemAction());
        menuManager.add(new CallBackAction());
        final Menu menu = menuManager.createContextMenu(callHistTableCtl
                .getShell());
        CallHistoryMenuListener callHistoryMenuListener = new CallHistoryMenuListener();
        callHistoryMenuListener.setParentMenu(menu);
        menu.addMenuListener(callHistoryMenuListener);
        // 将该对象设置为表格的菜单
        callHistTableCtl.setMenu(menu);
    }

    /**
     * 生成会议记录表格中的上下文菜单
     */
    private void createConfHistTableContextMenu()
    {
        MenuManager menuManager = new MenuManager();
        menuManager.add(new RemoveConfItemAction());
        final Menu menu = menuManager.createContextMenu(confHistTableCtl
                .getShell());
        ConfHistoryMenuListener confMenuListener = new ConfHistoryMenuListener();
        confMenuListener.setParentMenu(menu);
        menu.addMenuListener(confMenuListener);
        // 将该对象设置为表格的菜单
        confHistTableCtl.setMenu(menu);
    }

    private class RemoveCallItemAction extends Action
    {
        public RemoveCallItemAction()
        {
            setText(Messages.DELETE);
        }

        public void run()
        {
            // 获得当前的所选中的行
            StructuredSelection selection = (StructuredSelection) callHistTableViewer
                    .getSelection();
            // 获得数组对象的一个元素，也就是只有选中一行的情况
            STCallHistroyItem item = (STCallHistroyItem) selection
                    .getFirstElement();
            // 这里调用UC SDK的删除呼叫记录服务接口
            if (UCHistoryService.deleteCallHistData(item.recordID))
            {
                // 从表中删除该行
                callHistTableViewer.remove(item);
                freshCallHistory();
            }
        }
    }

    private class RemoveConfItemAction extends Action
    {
        public RemoveConfItemAction()
        {
            setText(Messages.DELETE);
        }

        public void run()
        {
            // 获得当前的所选中的行
            StructuredSelection selection = (StructuredSelection) confHistTableViewer
                    .getSelection();
            // 获得数组对象的一个元素，也就是只有选中一行的情况
            ConfHistItem item = (ConfHistItem) selection.getFirstElement();
            // 这里调用UC SDK的删除会议记录服务接口

            String convID = StringUtil
                    .bytesToString(item.getConvHistroyItem().convID);

            if (UCHistoryService.deleteConfHistData(convID))
            {
                // 从表中删除该行
                confHistTableViewer.remove(item);
                freshConvHistory();
            }
        }

    }

    private class CallBackAction extends Action
    {
        public CallBackAction()
        {
            setText(Messages.EsdkUCHistoryView_CALL_ACTION_CALL);
        }

        public void run()
        {
            // 获得当前的所选中的行
            StructuredSelection selection = (StructuredSelection) callHistTableViewer
                    .getSelection();
            // 获得数组对象的一个元素，也就是只有选中一行的情况
            STCallHistroyItem item = (STCallHistroyItem) selection
                    .getFirstElement();
            Participant participant = new Participant();
            ParticipantList participantList = new ParticipantList();

            participant.setUcAccount(StringUtil.bytesToString(item.ucAccount));
            participant.setNumber(StringUtil.bytesToString(item.callNum));

            participantList.addparticipants(participant);
            try
            {
                EsdkUCConvWindow window = EsdkUCConvWindow.getInstance();
                window.createUCConvWindow(participantList);
                window.makeCall(false);
                // window.open();
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }

    private void createCallTableHelpers()
    {
        callHistTableViewer.setContentProvider(new TableContentProvider());
        callHistTableViewer.setLabelProvider(new CallTableLabelProvider());
    }

    private void createConfTableHelpers()
    {
        confHistTableViewer.setContentProvider(new TableContentProvider());
        confHistTableViewer.setLabelProvider(new ConfTableLabelProvider());
    }

    private void setTableLayout(final Table table)
    {
        FormData fd = new FormData();
        fd.top = new FormAttachment(0, 0);
        fd.left = new FormAttachment(0, 0);
        fd.right = new FormAttachment(100, 0);
        fd.bottom = new FormAttachment(100, 0);
        table.setLayoutData(fd);

        TableLayout layout = new TableLayout();
        layout.addColumnData(new ColumnPixelData(60, false, true));
        layout.addColumnData(new ColumnWeightData(80, 100, true));
        layout.addColumnData(new ColumnWeightData(32, 100, true));
        layout.addColumnData(new ColumnPixelData(60, true, true));
        table.setLayout(layout);
    }

    private static class TableContentProvider implements
            IStructuredContentProvider
    {

        @Override
        public Object[] getElements(Object inputElement)
        {
            return ((List<?>) inputElement).toArray();
        }

        @Override
        public void dispose()
        {

        }

        @Override
        public void inputChanged(Viewer viewer, Object oldInput, Object newInput)
        {

        }

    }

    private static class CallTableLabelProvider implements ITableLabelProvider
    {
        @Override
        public Image getColumnImage(Object element, int columnIndex)
        {
            Image columImage = null;
            if (columnIndex == HistoryListConstants.CALL_STATUS_COLUMN)
            {
                STCallHistroyItem callHistroyItem = (STCallHistroyItem) element;

                columImage = UCHistoryService
                        .getHistoryTypeImage(callHistroyItem.callType);
            }
            return columImage;
        }

        @Override
        public String getColumnText(Object element, int columnIndex)
        {
            STCallHistroyItem item = (STCallHistroyItem) element;
            String columnText = "";
            switch (columnIndex)
            {
                case HistoryListConstants.NAME_COLUMN:
                {
                    // 底层传过来的字符是UTF-8编码,如果是中文,则需特别注意
                    columnText = StringUtil.bytesToUTF8String(item.callName);
                }
                    break;
                case HistoryListConstants.PHONE_COLUMN:

                    columnText = StringUtil.bytesToString(item.callNum);

                    if (StringUtil.isEmptyStr(columnText))
                    {
                        columnText = StringUtil.bytesToString(item.ucAccount);
                    }
                    break;
                case HistoryListConstants.CALL_DURATION_COLUMN:

                    columnText = PluginUtil.getFormatTime(item.duration);
                    break;
                case HistoryListConstants.CALL_TIME_COLUMN:

                    STTime time = item.startTime;
                    columnText = PluginUtil.getFormatDate(time);
                    break;
                default:
                    break;
            }
            return columnText;
        }

        @Override
        public void addListener(ILabelProviderListener listener)
        {

        }

        @Override
        public void dispose()
        {

        }

        @Override
        public boolean isLabelProperty(Object element, String property)
        {
            return false;
        }

        @Override
        public void removeListener(ILabelProviderListener listener)
        {
        }

    }

    private static class ConfTableLabelProvider implements ITableLabelProvider
    {
        @Override
        public Image getColumnImage(Object element, int columnIndex)
        {
            return null;
        }

        @Override
        public String getColumnText(Object element, int columnIndex)
        {
            ConfHistItem item = (ConfHistItem) element;
            String columnText = "";
            switch (columnIndex)
            {
                case HistoryListConstants.INITIATOR_COLUMN:

                    columnText = StringUtil.bytesToUTF8String(item
                            .getConvHistroyItem().compereName);
                    break;
                case HistoryListConstants.PARTICIPANTS_COLUMN:

                    List<STConfPartItem> confPartItems = item
                            .getConfPartItems();
                    StringBuffer buffer = new StringBuffer();
                    for (STConfPartItem confPartItem : confPartItems)
                    {
                        buffer.append(StringUtil
                                .bytesToUTF8String(confPartItem.partName));
                        buffer.append(", ");
                    }
                    columnText = buffer.substring(0, buffer.length() - 2);
                    break;
                case HistoryListConstants.CONF_DURATION_COLUMN:

                    columnText = PluginUtil.getFormatTime(item
                            .getConvHistroyItem().duration);
                    break;
                case HistoryListConstants.CONF_TIME_COLUMN:

                    STTime time = item.getConvHistroyItem().startTime;
                    columnText = PluginUtil.getFormatDate(time);
                    break;
                default:
                    break;
            }
            return columnText;
        }

        @Override
        public void addListener(ILabelProviderListener listener)
        {

        }

        @Override
        public void dispose()
        {

        }

        @Override
        public boolean isLabelProperty(Object element, String property)
        {
            return false;
        }

        @Override
        public void removeListener(ILabelProviderListener listener)
        {

        }

    }

    @Override
    public void setFocus()
    {
        callHistTableCtl.setFocus();
        confHistTableCtl.setFocus();
    }

    private static class CallHistoryMenuListener implements MenuListener
    {
        private Menu parentMenu;

        public Menu getParentMenu()
        {
            return parentMenu;
        }

        public void setParentMenu(Menu parentMenu)
        {
            this.parentMenu = parentMenu;
        }

        @Override
        public void menuHidden(MenuEvent arg0)
        {
        }

        @Override
        public void menuShown(MenuEvent arg0)
        {
            if (!GlobalConfiguration.getInstance().isSamtimeLogin()
                    || !GlobalConfiguration.getInstance().isUCLogin())
            {
                for (int i = 0; i < this.parentMenu.getItemCount(); i++)
                {
                    this.parentMenu.getItem(i).setEnabled(false);
                }
                return;
            }
            for (int i = 0; i < this.parentMenu.getItemCount(); i++)
            {
                if (1 == i && CallStatus.end != UCCallService.getCallStatus())
                {
                    this.parentMenu.getItem(1).setEnabled(false);
                }
                else
                {
                    this.parentMenu.getItem(i).setEnabled(true);
                }
            }
        }

    }

    private static class ConfHistoryMenuListener implements MenuListener
    {
        private Menu parentMenu;

        public Menu getParentMenu()
        {
            return parentMenu;
        }

        public void setParentMenu(Menu parentMenu)
        {
            this.parentMenu = parentMenu;
        }

        @Override
        public void menuHidden(MenuEvent arg0)
        {
        }

        @Override
        public void menuShown(MenuEvent arg0)
        {
            if (!GlobalConfiguration.getInstance().isSamtimeLogin()
                    || !GlobalConfiguration.getInstance().isUCLogin())
            {
                for (int i = 0; i < parentMenu.getItemCount(); i++)
                {
                    parentMenu.getItem(i).setEnabled(false);
                }
                return;
            }
            for (int i = 0; i < parentMenu.getItemCount(); i++)
            {
                parentMenu.getItem(i).setEnabled(true);
            }
        }
    }
}
